AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")

ENT.PrintName = "Custom Spawnpoint"
ENT.Model = "models/props_bts/Glados_Floorlight.mdl"
ENT.HP = 150


local function SendPly( ply , ent , bonoff )
	umsg.Start( "spawnpoint_user" )
		umsg.Entity( ply )
		umsg.Entity( ent )
		umsg.Bool(bonoff)
	umsg.End()
end


function ENT:Initialize()
	self:SetModel(self.Model)
	
	self:PhysicsInit( SOLID_VPHYSICS )// these 3 thngs makes it like a prop
	self:SetMoveType( MOVETYPE_VPHYSICS )// these 3 thngs makes it like a prop
	self:SetSolid( SOLID_VPHYSICS )// these 3 thngs makes it like a prop
	self:SetUseType( SIMPLE_USE )

	self.team = 1
end


function ENT:SpawnFunction( ply, tr)

	local SpawnPos = tr.HitPos + tr.HitNormal * 1
	local ent = ents.Create( "sent_spawnpoint" )
		ent:SetPos( SpawnPos )
		ent:Spawn()

	local phys = ent:GetPhysicsObject()
	phys:EnableMotion(false)
	phys:SetMass(150)
	ent:Activate()
	
	return ent
end


function ENT:Use( ply , caller )
	if !self.team then
		self.team = ply:Team()
	end

	local Point = SpawnPoints[ ply ]

	if Point == self then
		SpawnPoints[ ply ] = nil
		ply:PrintMessage(HUD_PRINTCENTER,"No longer your Spawnpoint")
		SendPly( ply , self , false )
	else
		SpawnPoints[ ply ] = self
		ply:PrintMessage(HUD_PRINTCENTER,"This is now your Spawnpoint. Press USE again to remove it")
		SendPly( ply , self , true )
	end

end


function ENT:OnTakeDamage( dmg )
	self.HP = self.HP - dmg:GetDamage()


	if self.HP < 1 then
		
		local explode = ents.Create( "env_explosion" )
		explode:SetPos( self:GetPos() )
		explode:Spawn()
		explode:SetKeyValue( "iMagnitude" , "0")
		explode:Fire( "Explode" , 0 , 0)

		self:Remove()

	end
end

function ENT:OnRemove()
	if SpawnPoints then
		for k,v in pairs(SpawnPoints) do
			if v == self then
				SpawnPoints[ k ] = nil
			end
		end
	end
end

SpawnPoints = {}

local function PlayerMove( ply )

	local Point = SpawnPoints[ ply ]

	if Point then
		if Point.team == ply:Team() then
			ply:SetPos(Point:GetPos() + Vector(0,0,10))
		end
	else
		return
	end
end

hook.Add("PlayerSpawn","SpawnPoints.Spawn",PlayerMove)
